package com.example.test.dialogfactory;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import easier.log.logger.Logger;
import java.util.Calendar;

public class MainActivity87 extends AppCompatActivity {

    private TimePicker timePicker;
    private Button confirm;
    private AlarmManager mAlarmManager;

    public static void start( Context context ) {

        Intent starter = new Intent( context, MainActivity87.class );
        context.startActivity( starter );
    }

    @Override
    protected void onCreate( Bundle savedInstanceState ) {

        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main87 );
        initView();

        mAlarmManager = (AlarmManager) getSystemService( ALARM_SERVICE );
    }

    private void initView() {

        Calendar calendar = Calendar.getInstance();

        timePicker = (TimePicker) findViewById( R.id.timePicker );
        timePicker.setOnTimeChangedListener( new OnTimeChangedListener() {
            @Override
            public void onTimeChanged( TimePicker view, int hourOfDay, int minute ) {

                calendar.set( Calendar.HOUR_OF_DAY, hourOfDay );
                calendar.set( Calendar.MINUTE, minute );
            }
        } );
        confirm = (Button) findViewById( R.id.confirm );
        confirm.setOnClickListener( new OnClickListener() {
            @Override
            public void onClick( View v ) {

                Intent intent = new Intent( MainActivity87.this, MainActivity87.class );
                intent.putExtra( "code", 200 );
                intent.putExtra( "message", "创建闹钟" );
                intent.putExtra( "data", "闹钟响了" );

                PendingIntent pendingIntent = PendingIntent.getActivity( MainActivity87.this, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT );

                mAlarmManager.set( AlarmManager.RTC, System.currentTimeMillis() + 10 * 1000, pendingIntent );

                Toast.makeText( v.getContext(), "已设置", Toast.LENGTH_SHORT ).show();
            }
        } );
    }


    @Override
    protected void onNewIntent( Intent intent ) {

        super.onNewIntent( intent );

        if ( intent.hasExtra( "code" ) ) {
            int code = intent.getIntExtra( "code", 0 );
            String message = intent.getStringExtra( "message" );
            String data = intent.getStringExtra( "data" );
            Logger.i( String.format( "%d %s %s", code, message, data ) );

            Toast.makeText( this, data, Toast.LENGTH_SHORT ).show();
        }
    }
}